package com.weir.workdemo.work01.future.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author weir
 */
@Slf4j
public class Convertor extends AbstractConverter{
    @Override
    public Map<String, Object> xmlToJson(String xml) {
        Map<String, Object> jsonObject = null;
        XmlMapper xmlMapper = new XmlMapper();
        try {
            jsonObject = xmlMapper.readValue(xml, Map.class);
        } catch (JsonProcessingException e) {
            log.error("xml转化json时异常：{}", e.getMessage(), e);
        }
        return jsonObject;
    }

    @Override
    public String jsonToXml(Map<String, Object> jsonObject) {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, false);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_1, false);
        xmlMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        try {
            return xmlMapper.writer().withoutRootName().writeValueAsString(jsonObject);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
